package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import security.Encryption;

import entities.Device;



public class AddDevice {
	private WindowsApplication windowsApp;
	private JPanel pnlAddDevice;
	private JTextField txtDeviceIP;
	private JTextField txtDevicePairKey;
	
	public AddDevice(){
		initialize();
	}
	public AddDevice(WindowsApplication windowsApp){
		this.windowsApp = windowsApp;
		initialize();
	}
	
	private void initialize(){
		pnlAddDevice = new JPanel();
		pnlAddDevice.setBounds(0, 0, 800, 600);
		pnlAddDevice.setLayout(null);
		
		JLabel lblTargetDeviceIp = new JLabel("Target Device IP:");
		lblTargetDeviceIp.setBounds(50, 100, 125, 22);
		pnlAddDevice.add(lblTargetDeviceIp);
		
		txtDeviceIP = new JTextField();
		txtDeviceIP.setBounds(187, 100, 200, 22);
		pnlAddDevice.add(txtDeviceIP);
		txtDeviceIP.setColumns(10);
		
		JLabel lblDevicePairKey = new JLabel("Target Pair Key:");
		lblDevicePairKey.setBounds(50, 125, 125, 22);
		pnlAddDevice.add(lblDevicePairKey);
		
		txtDevicePairKey = new JTextField();
		txtDevicePairKey.setBounds(187, 125, 200, 22);
		pnlAddDevice.add(txtDevicePairKey);
		
		JButton btnBack = new JButton("Back");
		btnBack.setBounds(691, 562, 97, 25);
		btnBack.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				windowsApp.getFrame().setContentPane(new Overview(windowsApp).getPanel());
			}
		});
		pnlAddDevice.add(btnBack);
		
		JButton btnAddDevice = new JButton("Add Device");
		btnAddDevice.setBounds(691, 99, 97, 25);
		btnAddDevice.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String ip = txtDeviceIP.getText();
				String pairKey = txtDevicePairKey.getText();
				
				//compare this pairKey to the targetDevice's pairkey
				String encPairKey = Encryption.digest(pairKey);
				windowsApp.getCSEP().getConnectionServiceImpPort().connectDevices(windowsApp.getDevice().getUUID(), ip, encPairKey);
				
				Device deTemp = windowsApp.getCSEP().getConnectionServiceImpPort().getDeviceByUUID(windowsApp.getDevice().getUUID());
				windowsApp.setDevice(deTemp);
				windowsApp.getFrame().setContentPane(new Overview(windowsApp).getPanel());
			}
		});
		pnlAddDevice.add(btnAddDevice);
	}
	
	public JPanel getPanel(){
		return pnlAddDevice;
	}
}
